package top.superflow.flow.condition

import org.apache.commons.jexl3.JexlBuilder
import top.superflow.exception.Exceptable
import top.superflow.flow.condition.exl.ExtExpressionCondition
import top.superflow.lang.StringUtils

class ExpressionEngine private extends Exceptable{


  def execute(extExpressionCondition: ExtExpressionCondition, variables : Map[String, Any]) : Any = {
    expressionNotNull(extExpressionCondition)

    extExpressionCondition.evaluate(variables)
  }

  private def expressionNotNull(extExpressionCondition: ExtExpressionCondition) = {
    if (extExpressionCondition == null) {
      throwRequestUnsupportedException("The executable expression can't be null!")
    }
  }

  def convert(expression : String) : ExtExpressionCondition = {
    if(StringUtils.isBlank(expression)){
      return null
    }
    val jexlExpression = ExpressionEngine.jexl.createExpression(expression)
    new ExtExpressionCondition(jexlExpression)
  }

  def isTrue(extExpressionCondition : ExtExpressionCondition, variables : Map[String, Any]) : Boolean = {
    expressionNotNull(extExpressionCondition)
    val result = extExpressionCondition.evaluate(variables)
    if(result == null || ! result.isInstanceOf[Boolean]){
      throwRequestUnsupportedException("The expression is not an boolean expression")
    }

    extExpressionCondition.asInstanceOf[Boolean]
  }


}

object ExpressionEngine {
  final val EXPECTING_PASS_INPUT_VARIABLE_NAME = "passInput"

  private val jexl = new JexlBuilder().strict(true).silent(false).create

  private val instance = new ExpressionEngine

  def getInstance = instance

}
